<template>
  <Div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
       <el-alert
          title="注意:只允许为第三级分类设置相关参数!"
          type="warning"
          :closable="false"
          show-icon
          >
        </el-alert>

        <el-row class="cat_pot">
          <el-col>
            <span>选择商品分类:</span>

            <el-cascader v-model="selectedCateKeys" :options="catelist" :props="{ expandTrigger:'hover',value:'cat_Id',label:'cat_Name',children:'children'}"
              @change="handleChange" clearable change-on-select></el-cascader>
          </el-col>


        </el-row>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="动态参数" name=1>
              <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisble=true">添加动态参数</el-button>
              <el-table :data="manyTableData" border stripe>
                <el-table-column type="expand">
                  <template v-slot="scope">
                    <el-tag v-for="(item,index) in scope.row.value" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>

                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="参数名称" prop="propertyName"></el-table-column>
                <el-table-column label="参数名称">
                  <template v-slot="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态参数" name=0>
               <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisble=true">添加静态参数</el-button>
               <el-table :data="onlyTableData" border stripe>
               <el-table-column type="expand">
                 <template v-slot="scope">
                   <el-tag v-for="(item,index) in scope.row.value" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                 
                   <el-input
                     class="input-new-tag"
                     v-if="scope.row.inputVisible"
                     v-model="scope.row.inputValue"
                     ref="saveTagInput"
                     size="small"
                     @keyup.enter.native="handleInputConfirm(scope.row)"
                     @blur="handleInputConfirm(scope.row)"
                   >
                   </el-input>
                   <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                 </template>
               </el-table-column>
               
                 <el-table-column type="index"></el-table-column>
                 <el-table-column label="参数名称" prop="propertyName"></el-table-column>
                 <el-table-column label="操作">
                   <template v-slot="scope">
                     <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
                     <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.id)">删除</el-button>
                   </template>
                 </el-table-column>
               </el-table>
            </el-tab-pane>
          </el-tabs>
    </el-card>

  <el-dialog
    :title="'添加'+titleText"
    :visible.sync="addDialogVisble"
    width="50%"
    @close="addDialogColsed"
    >
    <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="100px">
      <el-form-item :label="titleText" prop="propertyName">
        <el-input v-model="addFrom.propertyName"></el-input>
      </el-form-item>
      </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisble = false">取 消</el-button>
      <el-button type="primary" @click="addParams">确 定</el-button>
    </span>
  </el-dialog>


  <el-dialog
    :title="'修改'+titleText"
    :visible.sync="editDialogVisble"
    width="50%"
    @close="editDialogColsed"
    >
    <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="100px">
      <el-form-item :label="titleText" prop="attr_Write">
        <el-input v-model="editFrom.attr_Write"></el-input>
      </el-form-item>
      </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisble = false">取 消</el-button>
      <el-button type="primary" @click="editParams">确 定</el-button>
    </span>
  </el-dialog>
  </Div>
</template>

<script>
  export default{
    data(){
      return{
        catelist:[],
        selectedCateKeys:[],
        activeName:0,
        manyTableData:[],
        onlyTableData:[],
        addDialogVisble:false,
        addFrom:{
          propertyName:''
        },
        addFromRules:{
          propertyName:[
            {required:true,message:'请输入参数名称',trigger:'blur'}
          ]
        },
        editDialogVisble:false,
        editFrom:{

        },
        editFromRules:{
          propertyName:[
            {required:true,message:'请输入参数名称',trigger:'blur'}
          ]
        },
      }
    },
    created(){
      this.getCateList()
    },
    methods:{
     getCateList(){
      this.$http.get("https://localhost:44331/api/Commodity").then(res=>{
        if(res.status!== 200){
          return this.$message.error('获取数据失败')
        }
        this.catelist=this.getTreeData(res.data.data.data)
      })
      },
      show(){
        console.log(this.catelist)
      },
      getTreeData(data) {
                      // 循环遍历json数据
                      for (var i = 0; i < data.length; i++) {

                          if (data[i].children.length < 1) {
                              // children若为空数组，则将children设为undefined
                              data[i].children = undefined;
                          } else {
                              // children若不为空数组，则继续 递归调用 本方法
                              this.getTreeData(data[i].children);
                          }
                      }
                      return data;
                  },
       handleChange(){
         this.getParamsData()
       },
       handleTabClick(){
         this.getParamsData()
       },
      async getParamsData(){
         if (this.selectedCateKeys.length !== 3) {
              this.selectedCateKeys=[]
              this.manyTableData=[]
              this.onlyTableData=[]
              return
           }
         const{data:res}= await this.$http.get("https://localhost:44331/api/Categories",{params:{id:this.cateId,state:this.activeName}})
         if(res.status!== 200){return this.$message.error('获取参数失败')}
         if(res.data.length<1){
           this.onlyTableData=[],
           this.manyTableData=[]
           return
         }
         res.data.forEach(item=>{
           item.inputVisible=false
           item.inputValue=''
         })
         if(res.data[0].state===0){
           this.onlyTableData=res.data
          }else if(res.data[0].state===1){
           this.manyTableData=res.data
           }
       },
       addDialogColsed(){
         this.$refs.addFromRef.resetFields();
       },
       addParams(){
         this.$refs.addFromRef.validate(async valid=>{
           if(!valid){
             return
           }
         const{data:res}=await this.$http.post("https://localhost:44331/api/Categories/"+this.cateId+"/"+this.activeName,{
             propertyName:this.addFrom.propertyName
           })
           if(res.status!== 200){return this.$message.error('添加参数失败')}
           this.$message.success("添加成功"),
           this.addDialogVisble=false
           this.getParamsData()
         })
       },
      async showEditDialog(data){
       const{data:res}=await this.$http.get("https://localhost:44331/api/Categories/"+this.cateId+"/attributes/"+data)
       if(res.status!== 200){return this.$message.error('获取参数信息失败')}
       this.editFrom=res.data
         this.editDialogVisble=true
       },
       editDialogColsed(){
         this.$refs.editFromRef.resetFields();
       },
       editParams(){
       this.$refs.editFromRef.validate(async valid=>{
         if(!valid){return}
         const{data:res}=await this.$http.put("https://localhost:44331/api/Categories/"+this.cateId+"/attributes/"+this.editFrom.cat_Id,this.editFrom)
         if(res.status!== 200){return this.$message.error('修改参数失败')}
         this.$message.success("修改参数成功")
         this.getParamsData()
         this.editDialogVisble=false
       })
       },
      async removeParams(data){
       const confirmResult= await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                   confirmButtonText: '确定',
                   cancelButtonText: '取消',
                   type: 'warning'
                 }).catch(err=>err)
                 if(confirmResult !== 'confirm'){
                   return this.$message.info('已取消删除!')
                 }
               const{data:res} =await this.$http.delete("https://localhost:44331/api/Categories/"+this.cateId+"/attributes/"+data)
                if(res.status!== 200){return this.$message.error('删除参数失败')}
                this.$message.success("删除参数成功")
                this.getParamsData()
       },
      async handleInputConfirm(row){
         if(row.inputValue.trim().length===0){
           row.inputValue=''
           row.inputVisible=false
           return
         }
     row.value.push(row.inputValue.trim())
     row.inputValue=''
     row.inputVisible=false
   const{data:res}=await this.$http.put("https://localhost:44331/api/Categories/"+this.cateId+"/attributes/"+row.id,{
       attr_id:this.cateId,
       cat_Id:row.id,
       attr_Write:row.propertyName,
       attr_Sel:row.state,
       Attr_Vals:row.value
     })
     if(res.status!== 200){return this.$message.error('参数修改失败')}
       },
       showInput(row){
         row.inputVisible=true

          this.$nextTick(_ => {
                   this.$refs.saveTagInput.$refs.input.focus();
                 });
       },
       async saveAttrVals(row){
         const{data:res}=await this.$http.put("https://localhost:44331/api/Categories/"+this.cateId+"/attributes/"+row.id,{
             attr_id:this.cateId,
             cat_Id:row.id,
             attr_Write:row.propertyName,
             attr_Sel:row.state,
             Attr_Vals:row.value
           })
       },
       handleClose(index,row){
         row.value.splice(index,1)
         this.saveAttrVals(row)
       }
    },
    computed:{
      isBtnDisabled(){
        if(this.selectedCateKeys.length !== 3){
          return true
        }else{
          return false
        }
      },

      cateId(){
        if(this.selectedCateKeys.length === 3){
          return this.selectedCateKeys[2]
        }
        return null
      },
      titleText(){
        if(this.activeName==0){
          return'静态参数'
        }else{
          return'动态参数'
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .cat_pot{
    margin:15px 0 ;
  }
  .el-tag{
    margin: 10px;
  }
  .input-new-tag{
    width: 120px;
  }
</style>
